package com.test.jbpm.web.action;


import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


@Controller
@Scope("prototype")
public class FileUpLoadAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String tempPath = this.getInitParameter("tempDir"); // 临时文件保存路径
		String saveRoot = this.getInitParameter("saveRoot");// 服务器存储目录
		try {
			DiskFileUpload fu = new DiskFileUpload();
			fu.setHeaderEncoding("utf-8");//文件名称中中文乱码的解决方法
			fu.setSizeMax(1024 * 1024 * 200); // 最大200M
			fu.setSizeThreshold(1024 * 1024 * 2); // 超过2M启用缓存
			fu.setRepositoryPath(tempPath); // 缓存路径
			List fileItems = fu.parseRequest(request);
			Iterator i = fileItems.iterator();
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				String fileName = fi.getName();
				if (fileName != null) {
					// 修改保存的路径.
					int start = fileName.lastIndexOf("\\");
					fileName=fileName.substring(start + 1);
					fi.write(new File(saveRoot+ fileName));
					// 删除临时文件
					fi.delete();
				}
			}
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().print("{'success':true,'message':'上传成功'}");
		} catch (Exception e) {
			response.getWriter().print("{'success':false,'message':'上传失败'}");
		}

	}
}
